package util;

import context.*;

import java.awt.geom.*;//Line2D.Double;

// UTILITY Tilpasset klipping av TakSki

public class Firkant implements Context.Constants
{ //private static final boolean DEBUG=true; // Overriding Context.Constants.DEBUG

  private Point2D.Double p[]=new Point2D.Double[4];
  
  public Firkant(Point2D.Double p1,Point2D.Double p2,Point2D.Double p3,Point2D.Double p4)
  { this.p[0]=p1;
    this.p[1]=p2;
    this.p[2]=p3;
    this.p[3]=p4;    
  }
  
  public Firkant(GeneralPath path)
  {
    if(DEBUG) Debug.println("new Firkant: path="+path);
    int n=0;
    AffineTransform at=new AffineTransform(); // Unity
    PathIterator iterator=path.getPathIterator(at);
    while(!iterator.isDone())
    { double[] coords=new double[6];
      int type=iterator.currentSegment(coords);
      switch(type)
      {
        case PathIterator.SEG_MOVETO:
          if(DEBUG) Debug.println("Firkant: segment MOVETO="+edit(coords));
          p[0]=new Point2D.Double(coords[0],coords[1]); n=1;
          break;
        case PathIterator.SEG_LINETO:
          if(DEBUG) Debug.println("Firkant: segment LINETO="+edit(coords));
          if(n<4)
          { p[n]=new Point2D.Double(coords[0],coords[1]); n=n+1; }
          break;
      }
      iterator.next();
    }
    if(DEBUG) Debug.println("new Firkant: "+this);
  }
  
  private String edit(double[] coords)
  { String s="";
    for(int i=0;i<coords.length;i++)
    { if(i>0) s=s+',';
      s=s+coords[i]; 
    }
    return(s);
  }
  
  public void cut(double xCut,boolean left)
  { Line2D.Double line2=new Line2D.Double(p[1],p[0]);
    double Y2=snitt(line2,xCut);//,p[2].y,left);
    if(left) { if(p[1].x>xCut) p[1]=new Point2D.Double(xCut,Y2); }
    else     { if(p[0].x<xCut) p[0]=new Point2D.Double(xCut,Y2); }
            
    Line2D.Double line4=new Line2D.Double(p[2],p[3]);
    double Y4=snitt(line4,xCut);//,p[3].y,left);
    if(left) { if(p[2].x>xCut) p[2]=new Point2D.Double(xCut,Y4); }
    else     { if(p[3].x<xCut) p[3]=new Point2D.Double(xCut,Y4); }
  }
  
  double snitt(Line2D.Double line,double x)//,double y,boolean left)
  {
    
    double Y=line.y1+ (line.y2-line.y1)/(line.x2-line.x1)*(x-line.x1);
    return(Y);
  }
  
  
  public GeneralPath toGeneralPath()
  { GeneralPath path=new GeneralPath();
    path.moveTo((float)p[0].x,(float)p[0].y);
    path.lineTo((float)p[1].x,(float)p[1].y);
    path.lineTo((float)p[2].x,(float)p[2].y);
    path.lineTo((float)p[3].x,(float)p[3].y);
    path.closePath();
    return(path);
  }
  
  public String toString()
  { String s="Firkant[p1="+p[0]+",p2="+p[1]+",p3="+p[2]+",p4="+p[3]+']';
    return(s);
  }
  
}
